#ifndef __SINGLE_PRODUCER_CONSUMER_H
#define __SINGLE_PRODUCER_CONSUMER_H

#include <assert.h>
#include "define.h"

static const int MINIMUM_LIST_SIZE=8;

namespace engine
{
	/// \brief A single producer consumer implementation without critical sections.
	template <class SingleProducerConsumerType>
	class SingleProducerConsumer
	{
	public:
		/// Constructor
		SingleProducerConsumer();

		/// Destructor
		~SingleProducerConsumer();

		/// writeLock must be immediately followed by writeUnlock.  These two functions must be called in the same thread.
		/// \return A pointer to a block of data you can write to.
		SingleProducerConsumerType* writeLock(void);

		/// Call if you don't want to write to a block of data from writeLock() after all.
		/// Cancelling locks cancels all locks back up to the data passed.  So if you lock twice and cancel using the first lock, the second lock is ignored
		/// \param[in] cancelToLocation Which writeLock() to cancel.
		void cancelWriteLock(SingleProducerConsumerType* cancelToLocation);

		/// Call when you are done writing to a block of memory returned by writeLock()
		void writeUnlock(void);

		/// readLock must be immediately followed by readUnlock. These two functions must be called in the same thread.
		/// \retval 0 No data is availble to read
		/// \retval Non-zero The data previously written to, in another thread, by writeLock followed by writeUnlock.
		SingleProducerConsumerType* readLock(void);

		// Cancelling locks cancels all locks back up to the data passed.  So if you lock twice and cancel using the first lock, the second lock is ignored
		/// param[in] Which readLock() to cancel.
		void cancelReadLock(SingleProducerConsumerType* cancelToLocation);

		/// Signals that we are done reading the the data from the least recent call of readLock.
		/// At this point that pointer is no longer valid, and should no longer be read.
		void readUnlock(void);

		/// clear is not thread-safe and none of the lock or unlock functions should be called while it is running.
		void clear(void);

		/// This function will estimate how many elements are waiting to be read.  It's threadsafe enough that the value returned is stable, but not threadsafe enough to give accurate results.
		/// \return An ESTIMATE of how many data elements are waiting to be read
		int size(void) const;

		/// Make sure that the pointer we done reading for the call to readUnlock is the right pointer.
		/// param[in] A previous pointer returned by readLock()
		bool checkReadUnlockOrder(const SingleProducerConsumerType* data) const;

		/// Returns if readUnlock was called before readLock
		/// \return If the read is locked
		bool readIsLocked(void) const;

	private:
		struct DataPlusPtr
		{
			DataPlusPtr () { readyToRead = false; }
			SingleProducerConsumerType object;

			// Ready to read is so we can use an equality boolean comparison, in case the writePointer var is trashed while context switching.
			volatile bool readyToRead;
			volatile DataPlusPtr *next;
		};
		volatile DataPlusPtr *readAheadPointer;
		volatile DataPlusPtr *writeAheadPointer;
		volatile DataPlusPtr *readPointer;
		volatile DataPlusPtr *writePointer;
		unsigned readCount, writeCount;
	};

	template <class SingleProducerConsumerType>
	SingleProducerConsumer<SingleProducerConsumerType>::SingleProducerConsumer()
	{
		// Preallocate
		readPointer = new DataPlusPtr();
		writePointer = readPointer;
		readPointer->next = new DataPlusPtr();
		int listSize;
#ifdef _DEBUG
		assert(MINIMUM_LIST_SIZE >= 3);
#endif
		for (listSize=2; listSize < MINIMUM_LIST_SIZE; listSize++)
		{
			readPointer=readPointer->next;
			readPointer->next = new DataPlusPtr();
		}
		readPointer->next->next=writePointer; // last to next = start
		readPointer=writePointer;
		readAheadPointer=readPointer;
		writeAheadPointer=writePointer;
		readCount=writeCount=0;
	}

	template <class SingleProducerConsumerType>
	SingleProducerConsumer<SingleProducerConsumerType>::~SingleProducerConsumer()
	{
		volatile DataPlusPtr *next;
		readPointer=writeAheadPointer->next;
		while (readPointer!=writeAheadPointer)
		{
			next=readPointer->next;
			delete readPointer;
			readPointer=next;
		}
		delete readPointer;
	}

	template <class SingleProducerConsumerType>
	SingleProducerConsumerType* SingleProducerConsumer<SingleProducerConsumerType>::writeLock(void)
	{
		if (writeAheadPointer->next==readPointer ||
			writeAheadPointer->next->readyToRead==true)
		{
			volatile DataPlusPtr *originalNext=writeAheadPointer->next;
			writeAheadPointer->next=new DataPlusPtr;
			assert(writeAheadPointer->next);
			writeAheadPointer->next->next=originalNext;
		}

		volatile DataPlusPtr *last;
		last=writeAheadPointer;
		writeAheadPointer=writeAheadPointer->next;

		return (SingleProducerConsumerType*)last;
	}

	template <class SingleProducerConsumerType>
	void SingleProducerConsumer<SingleProducerConsumerType>::cancelWriteLock(SingleProducerConsumerType* cancelToLocation)
	{
		writeAheadPointer=(DataPlusPtr*)cancelToLocation;
	}

	template <class SingleProducerConsumerType>
	void SingleProducerConsumer<SingleProducerConsumerType>::writeUnlock(void)
	{
#ifdef _DEBUG
		assert(writePointer->next!=readPointer);
		assert(writePointer!=writeAheadPointer);
#endif

		writeCount++;
		// User is done with the data, allow send by updating the write pointer
		writePointer->readyToRead=true;
		writePointer=writePointer->next;
	}

	template <class SingleProducerConsumerType>
	SingleProducerConsumerType* SingleProducerConsumer<SingleProducerConsumerType>::readLock(void)
	{
		if (readAheadPointer==writePointer ||
			readAheadPointer->readyToRead==false)
		{
			return 0;
		}

		volatile DataPlusPtr *last;
		last=readAheadPointer;
		readAheadPointer=readAheadPointer->next;
		return (SingleProducerConsumerType*)last;
	}

	template <class SingleProducerConsumerType>
	void SingleProducerConsumer<SingleProducerConsumerType>::cancelReadLock(SingleProducerConsumerType* cancelToLocation)
	{
#ifdef _DEBUG
		assert(readPointer!=writePointer);
#endif
		readAheadPointer=(DataPlusPtr*)cancelToLocation;
	}

	template <class SingleProducerConsumerType>
	void SingleProducerConsumer<SingleProducerConsumerType>::readUnlock(void)
	{
#ifdef _DEBUG
		assert(readAheadPointer!=readPointer); // If hits, then called readUnlock before readLock
		assert(readPointer!=writePointer); // If hits, then called readUnlock when Read returns 0
#endif
		readCount++;

		// Allow writes to this memory block
		readPointer->readyToRead=false;
		readPointer=readPointer->next;
	}

	template <class SingleProducerConsumerType>
	void SingleProducerConsumer<SingleProducerConsumerType>::clear(void)
	{
		// Shrink the list down to MINIMUM_LIST_SIZE elements
		volatile DataPlusPtr *next;
		writePointer=readPointer->next;

		int listSize=1;
		next=readPointer->next;
		while (next!=readPointer)
		{
			listSize++;
			next=next->next;
		}

		while (listSize-- > MINIMUM_LIST_SIZE)
		{
			next=writePointer->next;
#ifdef _DEBUG
			assert(writePointer!=readPointer);
#endif
			delete writePointer;
			writePointer=next;
		}

		readPointer->next=writePointer;
		writePointer=readPointer;
		readAheadPointer=readPointer;
		writeAheadPointer=writePointer;
		readCount=writeCount=0;
	}

	template <class SingleProducerConsumerType>
	int SingleProducerConsumer<SingleProducerConsumerType>::size(void) const
	{
		return writeCount-readCount;
	}

	template <class SingleProducerConsumerType>
	bool SingleProducerConsumer<SingleProducerConsumerType>::checkReadUnlockOrder(const SingleProducerConsumerType* data) const
	{
		return const_cast<const SingleProducerConsumerType*>(&readPointer->object) == data;
	}


	template <class SingleProducerConsumerType>
	bool SingleProducerConsumer<SingleProducerConsumerType>::readIsLocked(void) const
	{
		return readAheadPointer!=readPointer;
	}       
}

#endif